<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores) - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlipc">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlipc.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlipc">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlipc">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlipc">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlipc">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlipc">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlipc">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlipc">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlipc">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlipc">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlipc">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlipc">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlipc">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlipc">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlipc">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlipc">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlipc">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlipc">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlipc">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlipc">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlipc">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlipc">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlipc">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlipc">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlipc">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlipc">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlipc">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlipc">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlipc">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlipc">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlipc">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlipc">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlipc">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlipc">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlipc">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlipc">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlipc">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlipc">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlipc">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlipc">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlipc">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlipc">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlipc">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlipc">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlipc">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlipc">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlipc">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlipc">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlipc">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlipc">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlipc">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlipc">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlipc">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlipc">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlipc">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlipc">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlipc">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlipc">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlipc">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlipc">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlipc">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlipc">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlipc">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlipc">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlipc">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlipc">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlipc">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlipc">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlipc">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlipc">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlipc">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlipc">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlipc">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlipc">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlipc">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlipc">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlipc">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlipc">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlipc">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlipc">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlipc">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlipc.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlipc">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlipc">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlipc">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlipc">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlipc">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlipc">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlipc">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlipc">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlipc">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlipc">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlipc">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlipc">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlipc">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlipc">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlipc">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlipc">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlipc">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlipc">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlipc">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlipc">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlipc">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlipc">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlipc">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlipc">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlipc">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlipc">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlipc">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlipc">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlipc">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlipc">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlipc">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlipc">5.35.1</a>
          <a class="dropdown-item active" href="perlipc.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlipc.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlipc.html">perlipc</a>
          <div id="more">
            (<a href="perlipc.txt">source</a>,
            <a href="https://metacpan.org/pod/perlipc">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlipc.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Signals">Signals</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Handling-the-SIGHUP-Signal-in-Daemons">Handling the SIGHUP Signal in Daemons</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Deferred-Signals-(Safe-Signals)">Deferred Signals (Safe Signals)</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Named-Pipes">Named Pipes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Using-open()-for-IPC">Using open() for IPC</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Filehandles">Filehandles</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Background-Processes">Background Processes</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Complete-Dissociation-of-Child-from-Parent">Complete Dissociation of Child from Parent</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Safe-Pipe-Opens">Safe Pipe Opens</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Avoiding-Pipe-Deadlocks">Avoiding Pipe Deadlocks</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Bidirectional-Communication-with-Another-Process">Bidirectional Communication with Another Process</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Bidirectional-Communication-with-Yourself">Bidirectional Communication with Yourself</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Sockets:-Client/Server-Communication">Sockets: Client/Server Communication</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Internet-Line-Terminators">Internet Line Terminators</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Internet-TCP-Clients-and-Servers">Internet TCP Clients and Servers</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Unix-Domain-TCP-Clients-and-Servers">Unix-Domain TCP Clients and Servers</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#TCP-Clients-with-IO::Socket">TCP Clients with IO::Socket</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlipc.html#A-Simple-Client">A Simple Client</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#A-Webget-Client">A Webget Client</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#Interactive-Client-with-IO::Socket">Interactive Client with IO::Socket</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#TCP-Servers-with-IO::Socket">TCP Servers with IO::Socket</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#UDP:-Message-Passing">UDP: Message Passing</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#SysV-IPC">SysV IPC</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#NOTES">NOTES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#BUGS">BUGS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#AUTHOR">AUTHOR</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlipc.html#SEE-ALSO">SEE ALSO</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlipc.html#NAME">#</a>NAME</h1>

<p>perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlipc.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>The basic IPC facilities of Perl are built out of the good old Unix signals, named pipes, pipe opens, the Berkeley socket routines, and SysV IPC calls. Each is used in slightly different situations.</p>

<h1 id="Signals"><a class="permalink" href="perlipc.html#Signals">#</a>Signals</h1>

<p>Perl uses a simple signal handling model: the %SIG hash contains names or references of user-installed signal handlers. These handlers will be called with an argument which is the name of the signal that triggered it. A signal may be generated intentionally from a particular keyboard sequence like control-C or control-Z, sent to you from another process, or triggered automatically by the kernel when special events transpire, like a child process exiting, your own process running out of stack space, or hitting a process file-size limit.</p>

<p>For example, to trap an interrupt signal, set up a handler like this:</p>

<pre><code>our $shucks;

sub catch_zap {
    my $signame = shift;
    $shucks++;
    die &quot;Somebody sent me a SIG$signame&quot;;
}
$SIG{INT} = __PACKAGE__ . &quot;::catch_zap&quot;;
$SIG{INT} = \&amp;catch_zap;  # best strategy</code></pre>

<p>Prior to Perl 5.8.0 it was necessary to do as little as you possibly could in your handler; notice how all we do is set a global variable and then raise an exception. That&#39;s because on most systems, libraries are not re-entrant; particularly, memory allocation and I/O routines are not. That meant that doing nearly <i>anything</i> in your handler could in theory trigger a memory fault and subsequent core dump - see <a href="perlipc.html#Deferred-Signals-%28Safe-Signals%29">&quot;Deferred Signals (Safe Signals)&quot;</a> below.</p>

<p>The names of the signals are the ones listed out by <code>kill -l</code> on your system, or you can retrieve them using the CPAN module <a href="./IPC::Signal.html">IPC::Signal</a>.</p>

<p>You may also choose to assign the strings <code>&quot;IGNORE&quot;</code> or <code>&quot;DEFAULT&quot;</code> as the handler, in which case Perl will try to discard the signal or do the default thing.</p>

<p>On most Unix platforms, the <code>CHLD</code> (sometimes also known as <code>CLD</code>) signal has special behavior with respect to a value of <code>&quot;IGNORE&quot;</code>. Setting <code>$SIG{CHLD}</code> to <code>&quot;IGNORE&quot;</code> on such a platform has the effect of not creating zombie processes when the parent process fails to <code>wait()</code> on its child processes (i.e., child processes are automatically reaped). Calling <code>wait()</code> with <code>$SIG{CHLD}</code> set to <code>&quot;IGNORE&quot;</code> usually returns <code>-1</code> on such platforms.</p>

<p>Some signals can be neither trapped nor ignored, such as the KILL and STOP (but not the TSTP) signals. Note that ignoring signals makes them disappear. If you only want them blocked temporarily without them getting lost you&#39;ll have to use the <code>POSIX</code> module&#39;s <a href="POSIX.html#sigprocmask">sigprocmask</a>.</p>

<p>Sending a signal to a negative process ID means that you send the signal to the entire Unix process group. This code sends a hang-up signal to all processes in the current process group, and also sets $SIG{HUP} to <code>&quot;IGNORE&quot;</code> so it doesn&#39;t kill itself:</p>

<pre><code># block scope for local
{
    local $SIG{HUP} = &quot;IGNORE&quot;;
    kill HUP =&gt; -getpgrp();
    # snazzy writing of: kill(&quot;HUP&quot;, -getpgrp())
}</code></pre>

<p>Another interesting signal to send is signal number zero. This doesn&#39;t actually affect a child process, but instead checks whether it&#39;s alive or has changed its UIDs.</p>

<pre><code>unless (kill 0 =&gt; $kid_pid) {
    warn &quot;something wicked happened to $kid_pid&quot;;
}</code></pre>

<p>Signal number zero may fail because you lack permission to send the signal when directed at a process whose real or saved UID is not identical to the real or effective UID of the sending process, even though the process is alive. You may be able to determine the cause of failure using <code>$!</code> or <code>%!</code>.</p>

<pre><code>unless (kill(0 =&gt; $pid) || $!{EPERM}) {
    warn &quot;$pid looks dead&quot;;
}</code></pre>

<p>You might also want to employ anonymous functions for simple signal handlers:</p>

<pre><code>$SIG{INT} = sub { die &quot;\nOutta here!\n&quot; };</code></pre>

<p>SIGCHLD handlers require some special care. If a second child dies while in the signal handler caused by the first death, we won&#39;t get another signal. So must loop here else we will leave the unreaped child as a zombie. And the next time two children die we get another zombie. And so on.</p>

<pre><code>use POSIX &quot;:sys_wait_h&quot;;
$SIG{CHLD} = sub {
    while ((my $child = waitpid(-1, WNOHANG)) &gt; 0) {
        $Kid_Status{$child} = $?;
    }
};
# do something that forks...</code></pre>

<p>Be careful: qx(), system(), and some modules for calling external commands do a fork(), then wait() for the result. Thus, your signal handler will be called. Because wait() was already called by system() or qx(), the wait() in the signal handler will see no more zombies and will therefore block.</p>

<p>The best way to prevent this issue is to use waitpid(), as in the following example:</p>

<pre><code>use POSIX &quot;:sys_wait_h&quot;; # for nonblocking read

my %children;

$SIG{CHLD} = sub {
    # don&#39;t change $! and $? outside handler
    local ($!, $?);
    while ( (my $pid = waitpid(-1, WNOHANG)) &gt; 0 ) {
        delete $children{$pid};
        cleanup_child($pid, $?);
    }
};

while (1) {
    my $pid = fork();
    die &quot;cannot fork&quot; unless defined $pid;
    if ($pid == 0) {
        # ...
        exit 0;
    } else {
        $children{$pid}=1;
        # ...
        system($command);
        # ...
   }
}</code></pre>

<p>Signal handling is also used for timeouts in Unix. While safely protected within an <code>eval{}</code> block, you set a signal handler to trap alarm signals and then schedule to have one delivered to you in some number of seconds. Then try your blocking operation, clearing the alarm when it&#39;s done but not before you&#39;ve exited your <code>eval{}</code> block. If it goes off, you&#39;ll use die() to jump out of the block.</p>

<p>Here&#39;s an example:</p>

<pre><code>my $ALARM_EXCEPTION = &quot;alarm clock restart&quot;;
eval {
    local $SIG{ALRM} = sub { die $ALARM_EXCEPTION };
    alarm 10;
    flock($fh, 2)    # blocking write lock
                    || die &quot;cannot flock: $!&quot;;
    alarm 0;
};
if ($@ &amp;&amp; $@ !~ quotemeta($ALARM_EXCEPTION)) { die }</code></pre>

<p>If the operation being timed out is system() or qx(), this technique is liable to generate zombies. If this matters to you, you&#39;ll need to do your own fork() and exec(), and kill the errant child process.</p>

<p>For more complex signal handling, you might see the standard POSIX module. Lamentably, this is almost entirely undocumented, but the <i>ext/POSIX/t/sigaction.t</i> file from the Perl source distribution has some examples in it.</p>

<h2 id="Handling-the-SIGHUP-Signal-in-Daemons"><a class="permalink" href="perlipc.html#Handling-the-SIGHUP-Signal-in-Daemons">#</a><a id="Handling"></a>Handling the SIGHUP Signal in Daemons</h2>

<p>A process that usually starts when the system boots and shuts down when the system is shut down is called a daemon (Disk And Execution MONitor). If a daemon process has a configuration file which is modified after the process has been started, there should be a way to tell that process to reread its configuration file without stopping the process. Many daemons provide this mechanism using a <code>SIGHUP</code> signal handler. When you want to tell the daemon to reread the file, simply send it the <code>SIGHUP</code> signal.</p>

<p>The following example implements a simple daemon, which restarts itself every time the <code>SIGHUP</code> signal is received. The actual code is located in the subroutine <code>code()</code>, which just prints some debugging info to show that it works; it should be replaced with the real code.</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions qw(catfile);

$| = 1;

# make the daemon cross-platform, so exec always calls the script
# itself with the right path, no matter how the script was invoked.
my $script = File::Basename::basename($0);
my $SELF  = catfile($FindBin::Bin, $script);

# POSIX unmasks the sigprocmask properly
$SIG{HUP} = sub {
    print &quot;got SIGHUP\n&quot;;
    exec($SELF, @ARGV)        || die &quot;$0: couldn&#39;t restart: $!&quot;;
};

code();

sub code {
    print &quot;PID: $$\n&quot;;
    print &quot;ARGV: @ARGV\n&quot;;
    my $count = 0;
    while (1) {
        sleep 2;
        print ++$count, &quot;\n&quot;;
    }
}</code></pre>

<h2 id="Deferred-Signals-(Safe-Signals)"><a class="permalink" href="perlipc.html#Deferred-Signals-(Safe-Signals)">#</a><a id="Deferred"></a><a id="Deferred-Signals-Safe-Signals"></a>Deferred Signals (Safe Signals)</h2>

<p>Before Perl 5.8.0, installing Perl code to deal with signals exposed you to danger from two things. First, few system library functions are re-entrant. If the signal interrupts while Perl is executing one function (like malloc(3) or printf(3)), and your signal handler then calls the same function again, you could get unpredictable behavior--often, a core dump. Second, Perl isn&#39;t itself re-entrant at the lowest levels. If the signal interrupts Perl while Perl is changing its own internal data structures, similarly unpredictable behavior may result.</p>

<p>There were two things you could do, knowing this: be paranoid or be pragmatic. The paranoid approach was to do as little as possible in your signal handler. Set an existing integer variable that already has a value, and return. This doesn&#39;t help you if you&#39;re in a slow system call, which will just restart. That means you have to <code>die</code> to longjmp(3) out of the handler. Even this is a little cavalier for the true paranoiac, who avoids <code>die</code> in a handler because the system <i>is</i> out to get you. The pragmatic approach was to say &quot;I know the risks, but prefer the convenience&quot;, and to do anything you wanted in your signal handler, and be prepared to clean up core dumps now and again.</p>

<p>Perl 5.8.0 and later avoid these problems by &quot;deferring&quot; signals. That is, when the signal is delivered to the process by the system (to the C code that implements Perl) a flag is set, and the handler returns immediately. Then at strategic &quot;safe&quot; points in the Perl interpreter (e.g. when it is about to execute a new opcode) the flags are checked and the Perl level handler from %SIG is executed. The &quot;deferred&quot; scheme allows much more flexibility in the coding of signal handlers as we know the Perl interpreter is in a safe state, and that we are not in a system library function when the handler is called. However the implementation does differ from previous Perls in the following ways:</p>

<dl>

<dt id="Long-running-opcodes"><a class="permalink" href="perlipc.html#Long-running-opcodes">#</a><a id="Long"></a>Long-running opcodes</dt>
<dd>

<p>As the Perl interpreter looks at signal flags only when it is about to execute a new opcode, a signal that arrives during a long-running opcode (e.g. a regular expression operation on a very large string) will not be seen until the current opcode completes.</p>

<p>If a signal of any given type fires multiple times during an opcode (such as from a fine-grained timer), the handler for that signal will be called only once, after the opcode completes; all other instances will be discarded. Furthermore, if your system&#39;s signal queue gets flooded to the point that there are signals that have been raised but not yet caught (and thus not deferred) at the time an opcode completes, those signals may well be caught and deferred during subsequent opcodes, with sometimes surprising results. For example, you may see alarms delivered even after calling <code>alarm(0)</code> as the latter stops the raising of alarms but does not cancel the delivery of alarms raised but not yet caught. Do not depend on the behaviors described in this paragraph as they are side effects of the current implementation and may change in future versions of Perl.</p>

</dd>
<dt id="Interrupting-IO"><a class="permalink" href="perlipc.html#Interrupting-IO">#</a><a id="Interrupting"></a>Interrupting IO</dt>
<dd>

<p>When a signal is delivered (e.g., SIGINT from a control-C) the operating system breaks into IO operations like <i>read</i>(2), which is used to implement Perl&#39;s readline() function, the <code>&lt;&gt;</code> operator. On older Perls the handler was called immediately (and as <code>read</code> is not &quot;unsafe&quot;, this worked well). With the &quot;deferred&quot; scheme the handler is <i>not</i> called immediately, and if Perl is using the system&#39;s <code>stdio</code> library that library may restart the <code>read</code> without returning to Perl to give it a chance to call the %SIG handler. If this happens on your system the solution is to use the <code>:perlio</code> layer to do IO--at least on those handles that you want to be able to break into with signals. (The <code>:perlio</code> layer checks the signal flags and calls %SIG handlers before resuming IO operation.)</p>

<p>The default in Perl 5.8.0 and later is to automatically use the <code>:perlio</code> layer.</p>

<p>Note that it is not advisable to access a file handle within a signal handler where that signal has interrupted an I/O operation on that same handle. While perl will at least try hard not to crash, there are no guarantees of data integrity; for example, some data might get dropped or written twice.</p>

<p>Some networking library functions like gethostbyname() are known to have their own implementations of timeouts which may conflict with your timeouts. If you have problems with such functions, try using the POSIX sigaction() function, which bypasses Perl safe signals. Be warned that this does subject you to possible memory corruption, as described above.</p>

<p>Instead of setting <code>$SIG{ALRM}</code>:</p>

<pre><code>local $SIG{ALRM} = sub { die &quot;alarm&quot; };</code></pre>

<p>try something like the following:</p>

<pre><code>use POSIX qw(SIGALRM);
POSIX::sigaction(SIGALRM,
                 POSIX::SigAction-&gt;new(sub { die &quot;alarm&quot; }))
         || die &quot;Error setting SIGALRM handler: $!\n&quot;;</code></pre>

<p>Another way to disable the safe signal behavior locally is to use the <code>Perl::Unsafe::Signals</code> module from CPAN, which affects all signals.</p>

</dd>
<dt id="Restartable-system-calls"><a class="permalink" href="perlipc.html#Restartable-system-calls">#</a><a id="Restartable"></a>Restartable system calls</dt>
<dd>

<p>On systems that supported it, older versions of Perl used the SA_RESTART flag when installing %SIG handlers. This meant that restartable system calls would continue rather than returning when a signal arrived. In order to deliver deferred signals promptly, Perl 5.8.0 and later do <i>not</i> use SA_RESTART. Consequently, restartable system calls can fail (with $! set to <code>EINTR</code>) in places where they previously would have succeeded.</p>

<p>The default <code>:perlio</code> layer retries <code>read</code>, <code>write</code> and <code>close</code> as described above; interrupted <code>wait</code> and <code>waitpid</code> calls will always be retried.</p>

</dd>
<dt id="Signals-as-&quot;faults&quot;"><a class="permalink" href="perlipc.html#Signals-as-%22faults%22">#</a><a id="Signals1"></a><a id="Signals-as-faults"></a>Signals as &quot;faults&quot;</dt>
<dd>

<p>Certain signals like SEGV, ILL, and BUS are generated by virtual memory addressing errors and similar &quot;faults&quot;. These are normally fatal: there is little a Perl-level handler can do with them. So Perl delivers them immediately rather than attempting to defer them.</p>

</dd>
<dt id="Signals-triggered-by-operating-system-state"><a class="permalink" href="perlipc.html#Signals-triggered-by-operating-system-state">#</a><a id="Signals2"></a>Signals triggered by operating system state</dt>
<dd>

<p>On some operating systems certain signal handlers are supposed to &quot;do something&quot; before returning. One example can be CHLD or CLD, which indicates a child process has completed. On some operating systems the signal handler is expected to <code>wait</code> for the completed child process. On such systems the deferred signal scheme will not work for those signals: it does not do the <code>wait</code>. Again the failure will look like a loop as the operating system will reissue the signal because there are completed child processes that have not yet been <code>wait</code>ed for.</p>

</dd>
</dl>

<p>If you want the old signal behavior back despite possible memory corruption, set the environment variable <code>PERL_SIGNALS</code> to <code>&quot;unsafe&quot;</code>. This feature first appeared in Perl 5.8.1.</p>

<h1 id="Named-Pipes"><a class="permalink" href="perlipc.html#Named-Pipes">#</a><a id="Named"></a>Named Pipes</h1>

<p>A named pipe (often referred to as a FIFO) is an old Unix IPC mechanism for processes communicating on the same machine. It works just like regular anonymous pipes, except that the processes rendezvous using a filename and need not be related.</p>

<p>To create a named pipe, use the <code>POSIX::mkfifo()</code> function.</p>

<pre><code>use POSIX qw(mkfifo);
mkfifo($path, 0700)     ||  die &quot;mkfifo $path failed: $!&quot;;</code></pre>

<p>You can also use the Unix command mknod(1), or on some systems, mkfifo(1). These may not be in your normal path, though.</p>

<pre><code># system return val is backwards, so &amp;&amp; not ||
#
$ENV{PATH} .= &quot;:/etc:/usr/etc&quot;;
if  (      system(&quot;mknod&quot;,  $path, &quot;p&quot;)
        &amp;&amp; system(&quot;mkfifo&quot;, $path) )
{
    die &quot;mk{nod,fifo} $path failed&quot;;
}</code></pre>

<p>A fifo is convenient when you want to connect a process to an unrelated one. When you open a fifo, the program will block until there&#39;s something on the other end.</p>

<p>For example, let&#39;s say you&#39;d like to have your <i>.signature</i> file be a named pipe that has a Perl program on the other end. Now every time any program (like a mailer, news reader, finger program, etc.) tries to read from that file, the reading program will read the new signature from your program. We&#39;ll use the pipe-checking file-test operator, <b>-p</b>, to find out whether anyone (or anything) has accidentally removed our fifo.</p>

<pre><code>chdir();    # go home
my $FIFO = &quot;.signature&quot;;

while (1) {
    unless (-p $FIFO) {
        unlink $FIFO;   # discard any failure, will catch later
        require POSIX;  # delayed loading of heavy module
        POSIX::mkfifo($FIFO, 0700)
                              || die &quot;can&#39;t mkfifo $FIFO: $!&quot;;
    }

    # next line blocks till there&#39;s a reader
    open (my $fh, &quot;&gt;&quot;, $FIFO) || die &quot;can&#39;t open $FIFO: $!&quot;;
    print $fh &quot;John Smith (smith\@host.org)\n&quot;, `fortune -s`;
    close($fh)                || die &quot;can&#39;t close $FIFO: $!&quot;;
    sleep 2;                # to avoid dup signals
}</code></pre>

<h1 id="Using-open()-for-IPC"><a class="permalink" href="perlipc.html#Using-open()-for-IPC">#</a><a id="Using"></a><a id="Using-open-for-IPC"></a>Using open() for IPC</h1>

<p>Perl&#39;s basic open() statement can also be used for unidirectional interprocess communication by specifying the open mode as <code>|-</code> or <code>-|</code>. Here&#39;s how to start something up in a child process you intend to write to:</p>

<pre><code>open(my $spooler, &quot;|-&quot;, &quot;cat -v | lpr -h 2&gt;/dev/null&quot;)
                    || die &quot;can&#39;t fork: $!&quot;;
local $SIG{PIPE} = sub { die &quot;spooler pipe broke&quot; };
print $spooler &quot;stuff\n&quot;;
close $spooler      || die &quot;bad spool: $! $?&quot;;</code></pre>

<p>And here&#39;s how to start up a child process you intend to read from:</p>

<pre><code>open(my $status, &quot;-|&quot;, &quot;netstat -an 2&gt;&amp;1&quot;)
                    || die &quot;can&#39;t fork: $!&quot;;
while (&lt;$status&gt;) {
    next if /^(tcp|udp)/;
    print;
}
close $status       || die &quot;bad netstat: $! $?&quot;;</code></pre>

<p>Be aware that these operations are full Unix forks, which means they may not be correctly implemented on all alien systems. See <a href="perlport.html#open">&quot;open&quot; in perlport</a> for portability details.</p>

<p>In the two-argument form of open(), a pipe open can be achieved by either appending or prepending a pipe symbol to the second argument:</p>

<pre><code>open(my $spooler, &quot;| cat -v | lpr -h 2&gt;/dev/null&quot;)
                    || die &quot;can&#39;t fork: $!&quot;;
open(my $status, &quot;netstat -an 2&gt;&amp;1 |&quot;)
                    || die &quot;can&#39;t fork: $!&quot;;</code></pre>

<p>This can be used even on systems that do not support forking, but this possibly allows code intended to read files to unexpectedly execute programs. If one can be sure that a particular program is a Perl script expecting filenames in @ARGV using the two-argument form of open() or the <code>&lt;&gt;</code> operator, the clever programmer can write something like this:</p>

<pre><code class="plaintext">% program f1 &quot;cmd1|&quot; - f2 &quot;cmd2|&quot; f3 &lt; tmpfile</code></pre>

<p>and no matter which sort of shell it&#39;s called from, the Perl program will read from the file <i>f1</i>, the process <i>cmd1</i>, standard input (<i>tmpfile</i> in this case), the <i>f2</i> file, the <i>cmd2</i> command, and finally the <i>f3</i> file. Pretty nifty, eh?</p>

<p>You might notice that you could use backticks for much the same effect as opening a pipe for reading:</p>

<pre><code>print grep { !/^(tcp|udp)/ } `netstat -an 2&gt;&amp;1`;
die &quot;bad netstatus ($?)&quot; if $?;</code></pre>

<p>While this is true on the surface, it&#39;s much more efficient to process the file one line or record at a time because then you don&#39;t have to read the whole thing into memory at once. It also gives you finer control of the whole process, letting you kill off the child process early if you&#39;d like.</p>

<p>Be careful to check the return values from both open() and close(). If you&#39;re <i>writing</i> to a pipe, you should also trap SIGPIPE. Otherwise, think of what happens when you start up a pipe to a command that doesn&#39;t exist: the open() will in all likelihood succeed (it only reflects the fork()&#39;s success), but then your output will fail--spectacularly. Perl can&#39;t know whether the command worked, because your command is actually running in a separate process whose exec() might have failed. Therefore, while readers of bogus commands return just a quick EOF, writers to bogus commands will get hit with a signal, which they&#39;d best be prepared to handle. Consider:</p>

<pre><code>open(my $fh, &quot;|-&quot;, &quot;bogus&quot;) || die &quot;can&#39;t fork: $!&quot;;
print $fh &quot;bang\n&quot;;         #  neither necessary nor sufficient
                            #  to check print retval!
close($fh)                  || die &quot;can&#39;t close: $!&quot;;</code></pre>

<p>The reason for not checking the return value from print() is because of pipe buffering; physical writes are delayed. That won&#39;t blow up until the close, and it will blow up with a SIGPIPE. To catch it, you could use this:</p>

<pre><code>$SIG{PIPE} = &quot;IGNORE&quot;;
open(my $fh, &quot;|-&quot;, &quot;bogus&quot;) || die &quot;can&#39;t fork: $!&quot;;
print $fh &quot;bang\n&quot;;
close($fh)                  || die &quot;can&#39;t close: status=$?&quot;;</code></pre>

<h2 id="Filehandles"><a class="permalink" href="perlipc.html#Filehandles">#</a>Filehandles</h2>

<p>Both the main process and any child processes it forks share the same STDIN, STDOUT, and STDERR filehandles. If both processes try to access them at once, strange things can happen. You may also want to close or reopen the filehandles for the child. You can get around this by opening your pipe with open(), but on some systems this means that the child process cannot outlive the parent.</p>

<h2 id="Background-Processes"><a class="permalink" href="perlipc.html#Background-Processes">#</a><a id="Background"></a>Background Processes</h2>

<p>You can run a command in the background with:</p>

<pre><code>system(&quot;cmd &amp;&quot;);</code></pre>

<p>The command&#39;s STDOUT and STDERR (and possibly STDIN, depending on your shell) will be the same as the parent&#39;s. You won&#39;t need to catch SIGCHLD because of the double-fork taking place; see below for details.</p>

<h2 id="Complete-Dissociation-of-Child-from-Parent"><a class="permalink" href="perlipc.html#Complete-Dissociation-of-Child-from-Parent">#</a><a id="Complete"></a>Complete Dissociation of Child from Parent</h2>

<p>In some cases (starting server processes, for instance) you&#39;ll want to completely dissociate the child process from the parent. This is often called daemonization. A well-behaved daemon will also chdir() to the root directory so it doesn&#39;t prevent unmounting the filesystem containing the directory from which it was launched, and redirect its standard file descriptors from and to <i>/dev/null</i> so that random output doesn&#39;t wind up on the user&#39;s terminal.</p>

<pre><code>use POSIX &quot;setsid&quot;;

sub daemonize {
    chdir(&quot;/&quot;)                     || die &quot;can&#39;t chdir to /: $!&quot;;
    open(STDIN,  &quot;&lt;&quot;, &quot;/dev/null&quot;) || die &quot;can&#39;t read /dev/null: $!&quot;;
    open(STDOUT, &quot;&gt;&quot;, &quot;/dev/null&quot;) || die &quot;can&#39;t write /dev/null: $!&quot;;
    defined(my $pid = fork())      || die &quot;can&#39;t fork: $!&quot;;
    exit if $pid;              # non-zero now means I am the parent
    (setsid() != -1)           || die &quot;Can&#39;t start a new session: $!&quot;;
    open(STDERR, &quot;&gt;&amp;&quot;, STDOUT) || die &quot;can&#39;t dup stdout: $!&quot;;
}</code></pre>

<p>The fork() has to come before the setsid() to ensure you aren&#39;t a process group leader; the setsid() will fail if you are. If your system doesn&#39;t have the setsid() function, open <i>/dev/tty</i> and use the <code>TIOCNOTTY</code> ioctl() on it instead. See tty(4) for details.</p>

<p>Non-Unix users should check their <code><i>Your_OS</i>::Process</code> module for other possible solutions.</p>

<h2 id="Safe-Pipe-Opens"><a class="permalink" href="perlipc.html#Safe-Pipe-Opens">#</a><a id="Safe"></a>Safe Pipe Opens</h2>

<p>Another interesting approach to IPC is making your single program go multiprocess and communicate between--or even amongst--yourselves. The two-argument form of the open() function will accept a file argument of either <code>&quot;-|&quot;</code> or <code>&quot;|-&quot;</code> to do a very interesting thing: it forks a child connected to the filehandle you&#39;ve opened. The child is running the same program as the parent. This is useful for safely opening a file when running under an assumed UID or GID, for example. If you open a pipe <i>to</i> minus, you can write to the filehandle you opened and your kid will find it in <i>his</i> STDIN. If you open a pipe <i>from</i> minus, you can read from the filehandle you opened whatever your kid writes to <i>his</i> STDOUT.</p>

<pre><code>my $PRECIOUS = &quot;/path/to/some/safe/file&quot;;
my $sleep_count;
my $pid;
my $kid_to_write;

do {
    $pid = open($kid_to_write, &quot;|-&quot;);
    unless (defined $pid) {
        warn &quot;cannot fork: $!&quot;;
        die &quot;bailing out&quot; if $sleep_count++ &gt; 6;
        sleep 10;
    }
} until defined $pid;

if ($pid) {                 # I am the parent
    print $kid_to_write @some_data;
    close($kid_to_write)    || warn &quot;kid exited $?&quot;;
} else {                    # I am the child
    # drop permissions in setuid and/or setgid programs:
    ($&gt;, $)) = ($&lt;, $();
    open (my $outfile, &quot;&gt;&quot;, $PRECIOUS)
                            || die &quot;can&#39;t open $PRECIOUS: $!&quot;;
    while (&lt;STDIN&gt;) {
        print $outfile;     # child STDIN is parent $kid_to_write
    }
    close($outfile)         || die &quot;can&#39;t close $PRECIOUS: $!&quot;;
    exit(0);                # don&#39;t forget this!!
}</code></pre>

<p>Another common use for this construct is when you need to execute something without the shell&#39;s interference. With system(), it&#39;s straightforward, but you can&#39;t use a pipe open or backticks safely. That&#39;s because there&#39;s no way to stop the shell from getting its hands on your arguments. Instead, use lower-level control to call exec() directly.</p>

<p>Here&#39;s a safe backtick or pipe open for read:</p>

<pre><code>my $pid = open(my $kid_to_read, &quot;-|&quot;);
defined($pid)            || die &quot;can&#39;t fork: $!&quot;;

if ($pid) {             # parent
    while (&lt;$kid_to_read&gt;) {
                        # do something interesting
    }
    close($kid_to_read)  || warn &quot;kid exited $?&quot;;

} else {                # child
    ($&gt;, $)) = ($&lt;, $(); # suid only
    exec($program, @options, @args)
                         || die &quot;can&#39;t exec program: $!&quot;;
    # NOTREACHED
}</code></pre>

<p>And here&#39;s a safe pipe open for writing:</p>

<pre><code>my $pid = open(my $kid_to_write, &quot;|-&quot;);
defined($pid)            || die &quot;can&#39;t fork: $!&quot;;

$SIG{PIPE} = sub { die &quot;whoops, $program pipe broke&quot; };

if ($pid) {             # parent
    print $kid_to_write @data;
    close($kid_to_write) || warn &quot;kid exited $?&quot;;

} else {                # child
    ($&gt;, $)) = ($&lt;, $();
    exec($program, @options, @args)
                         || die &quot;can&#39;t exec program: $!&quot;;
    # NOTREACHED
}</code></pre>

<p>It is very easy to dead-lock a process using this form of open(), or indeed with any use of pipe() with multiple subprocesses. The example above is &quot;safe&quot; because it is simple and calls exec(). See <a href="perlipc.html#Avoiding-Pipe-Deadlocks">&quot;Avoiding Pipe Deadlocks&quot;</a> for general safety principles, but there are extra gotchas with Safe Pipe Opens.</p>

<p>In particular, if you opened the pipe using <code>open $fh, &quot;|-&quot;</code>, then you cannot simply use close() in the parent process to close an unwanted writer. Consider this code:</p>

<pre><code>my $pid = open(my $writer, &quot;|-&quot;);        # fork open a kid
defined($pid)               || die &quot;first fork failed: $!&quot;;
if ($pid) {
    if (my $sub_pid = fork()) {
        defined($sub_pid)   || die &quot;second fork failed: $!&quot;;
        close($writer)      || die &quot;couldn&#39;t close writer: $!&quot;;
        # now do something else...
    }
    else {
        # first write to $writer
        # ...
        # then when finished
        close($writer)      || die &quot;couldn&#39;t close writer: $!&quot;;
        exit(0);
    }
}
else {
    # first do something with STDIN, then
    exit(0);
}</code></pre>

<p>In the example above, the true parent does not want to write to the $writer filehandle, so it closes it. However, because $writer was opened using <code>open $fh, &quot;|-&quot;</code>, it has a special behavior: closing it calls waitpid() (see <a href="perlfunc.html#waitpid">&quot;waitpid&quot; in perlfunc</a>), which waits for the subprocess to exit. If the child process ends up waiting for something happening in the section marked &quot;do something else&quot;, you have deadlock.</p>

<p>This can also be a problem with intermediate subprocesses in more complicated code, which will call waitpid() on all open filehandles during global destruction--in no predictable order.</p>

<p>To solve this, you must manually use pipe(), fork(), and the form of open() which sets one file descriptor to another, as shown below:</p>

<pre><code>pipe(my $reader, my $writer)   || die &quot;pipe failed: $!&quot;;
my $pid = fork();
defined($pid)                  || die &quot;first fork failed: $!&quot;;
if ($pid) {
    close $reader;
    if (my $sub_pid = fork()) {
        defined($sub_pid)      || die &quot;first fork failed: $!&quot;;
        close($writer)         || die &quot;can&#39;t close writer: $!&quot;;
    }
    else {
        # write to $writer...
        # ...
        # then  when finished
        close($writer)         || die &quot;can&#39;t close writer: $!&quot;;
        exit(0);
    }
    # write to $writer...
}
else {
    open(STDIN, &quot;&lt;&amp;&quot;, $reader) || die &quot;can&#39;t reopen STDIN: $!&quot;;
    close($writer)             || die &quot;can&#39;t close writer: $!&quot;;
    # do something...
    exit(0);
}</code></pre>

<p>Since Perl 5.8.0, you can also use the list form of <code>open</code> for pipes. This is preferred when you wish to avoid having the shell interpret metacharacters that may be in your command string.</p>

<p>So for example, instead of using:</p>

<pre><code>open(my $ps_pipe, &quot;-|&quot;, &quot;ps aux&quot;) || die &quot;can&#39;t open ps pipe: $!&quot;;</code></pre>

<p>One would use either of these:</p>

<pre><code>open(my $ps_pipe, &quot;-|&quot;, &quot;ps&quot;, &quot;aux&quot;)
                                  || die &quot;can&#39;t open ps pipe: $!&quot;;

my @ps_args = qw[ ps aux ];
open(my $ps_pipe, &quot;-|&quot;, @ps_args)
                                  || die &quot;can&#39;t open @ps_args|: $!&quot;;</code></pre>

<p>Because there are more than three arguments to open(), it forks the ps(1) command <i>without</i> spawning a shell, and reads its standard output via the <code>$ps_pipe</code> filehandle. The corresponding syntax to <i>write</i> to command pipes is to use <code>&quot;|-&quot;</code> in place of <code>&quot;-|&quot;</code>.</p>

<p>This was admittedly a rather silly example, because you&#39;re using string literals whose content is perfectly safe. There is therefore no cause to resort to the harder-to-read, multi-argument form of pipe open(). However, whenever you cannot be assured that the program arguments are free of shell metacharacters, the fancier form of open() should be used. For example:</p>

<pre><code>my @grep_args = (&quot;egrep&quot;, &quot;-i&quot;, $some_pattern, @many_files);
open(my $grep_pipe, &quot;-|&quot;, @grep_args)
                    || die &quot;can&#39;t open @grep_args|: $!&quot;;</code></pre>

<p>Here the multi-argument form of pipe open() is preferred because the pattern and indeed even the filenames themselves might hold metacharacters.</p>

<h2 id="Avoiding-Pipe-Deadlocks"><a class="permalink" href="perlipc.html#Avoiding-Pipe-Deadlocks">#</a><a id="Avoiding"></a>Avoiding Pipe Deadlocks</h2>

<p>Whenever you have more than one subprocess, you must be careful that each closes whichever half of any pipes created for interprocess communication it is not using. This is because any child process reading from the pipe and expecting an EOF will never receive it, and therefore never exit. A single process closing a pipe is not enough to close it; the last process with the pipe open must close it for it to read EOF.</p>

<p>Certain built-in Unix features help prevent this most of the time. For instance, filehandles have a &quot;close on exec&quot; flag, which is set <i>en masse</i> under control of the <code>$^F</code> variable. This is so any filehandles you didn&#39;t explicitly route to the STDIN, STDOUT or STDERR of a child <i>program</i> will be automatically closed.</p>

<p>Always explicitly and immediately call close() on the writable end of any pipe, unless that process is actually writing to it. Even if you don&#39;t explicitly call close(), Perl will still close() all filehandles during global destruction. As previously discussed, if those filehandles have been opened with Safe Pipe Open, this will result in calling waitpid(), which may again deadlock.</p>

<h2 id="Bidirectional-Communication-with-Another-Process"><a class="permalink" href="perlipc.html#Bidirectional-Communication-with-Another-Process">#</a><a id="Bidirectional"></a>Bidirectional Communication with Another Process</h2>

<p>While this works reasonably well for unidirectional communication, what about bidirectional communication? The most obvious approach doesn&#39;t work:</p>

<pre><code># THIS DOES NOT WORK!!
open(my $prog_for_reading_and_writing, &quot;| some program |&quot;)</code></pre>

<p>If you forget to <code>use warnings</code>, you&#39;ll miss out entirely on the helpful diagnostic message:</p>

<pre><code class="plaintext">Can&#39;t do bidirectional pipe at -e line 1.</code></pre>

<p>If you really want to, you can use the standard open2() from the <a href="./IPC::Open2.html">IPC::Open2</a> module to catch both ends. There&#39;s also an open3() in <a href="./IPC::Open3.html">IPC::Open3</a> for tridirectional I/O so you can also catch your child&#39;s STDERR, but doing so would then require an awkward select() loop and wouldn&#39;t allow you to use normal Perl input operations.</p>

<p>If you look at its source, you&#39;ll see that open2() uses low-level primitives like the pipe() and exec() syscalls to create all the connections. Although it might have been more efficient by using socketpair(), this would have been even less portable than it already is. The open2() and open3() functions are unlikely to work anywhere except on a Unix system, or at least one purporting POSIX compliance.</p>

<p>Here&#39;s an example of using open2():</p>

<pre><code>use IPC::Open2;
my $pid = open2(my $reader, my $writer, &quot;cat -un&quot;);
print $writer &quot;stuff\n&quot;;
my $got = &lt;$reader&gt;;
waitpid $pid, 0;</code></pre>

<p>The problem with this is that buffering is really going to ruin your day. Even though your <code>$writer</code> filehandle is auto-flushed so the process on the other end gets your data in a timely manner, you can&#39;t usually do anything to force that process to give its data to you in a similarly quick fashion. In this special case, we could actually so, because we gave <i>cat</i> a <b>-u</b> flag to make it unbuffered. But very few commands are designed to operate over pipes, so this seldom works unless you yourself wrote the program on the other end of the double-ended pipe.</p>

<p>A solution to this is to use a library which uses pseudottys to make your program behave more reasonably. This way you don&#39;t have to have control over the source code of the program you&#39;re using. The <code>Expect</code> module from CPAN also addresses this kind of thing. This module requires two other modules from CPAN, <code>IO::Pty</code> and <code>IO::Stty</code>. It sets up a pseudo terminal to interact with programs that insist on talking to the terminal device driver. If your system is supported, this may be your best bet.</p>

<h2 id="Bidirectional-Communication-with-Yourself"><a class="permalink" href="perlipc.html#Bidirectional-Communication-with-Yourself">#</a><a id="Bidirectional1"></a>Bidirectional Communication with Yourself</h2>

<p>If you want, you may make low-level pipe() and fork() syscalls to stitch this together by hand. This example only talks to itself, but you could reopen the appropriate handles to STDIN and STDOUT and call other processes. (The following example lacks proper error checking.)</p>

<pre><code>#!/usr/bin/perl
# pipe1 - bidirectional communication using two pipe pairs
#         designed for the socketpair-challenged
use strict;
use warnings;
use IO::Handle;  # enable autoflush method before Perl 5.14
pipe(my $parent_rdr, my $child_wtr);  # XXX: check failure?
pipe(my $child_rdr,  my $parent_wtr); # XXX: check failure?
$child_wtr-&gt;autoflush(1);
$parent_wtr-&gt;autoflush(1);

if ($pid = fork()) {
    close $parent_rdr;
    close $parent_wtr;
    print $child_wtr &quot;Parent Pid $$ is sending this\n&quot;;
    chomp(my $line = &lt;$child_rdr&gt;);
    print &quot;Parent Pid $$ just read this: &#39;$line&#39;\n&quot;;
    close $child_rdr; close $child_wtr;
    waitpid($pid, 0);
} else {
    die &quot;cannot fork: $!&quot; unless defined $pid;
    close $child_rdr;
    close $child_wtr;
    chomp(my $line = &lt;$parent_rdr&gt;);
    print &quot;Child Pid $$ just read this: &#39;$line&#39;\n&quot;;
    print $parent_wtr &quot;Child Pid $$ is sending this\n&quot;;
    close $parent_rdr;
    close $parent_wtr;
    exit(0);
}</code></pre>

<p>But you don&#39;t actually have to make two pipe calls. If you have the socketpair() system call, it will do this all for you.</p>

<pre><code>#!/usr/bin/perl
# pipe2 - bidirectional communication using socketpair
#   &quot;the best ones always go both ways&quot;

use strict;
use warnings;
use Socket;
use IO::Handle;  # enable autoflush method before Perl 5.14

# We say AF_UNIX because although *_LOCAL is the
# POSIX 1003.1g form of the constant, many machines
# still don&#39;t have it.
socketpair(my $child, my $parent, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
                            ||  die &quot;socketpair: $!&quot;;

$child-&gt;autoflush(1);
$parent-&gt;autoflush(1);

if ($pid = fork()) {
    close $parent;
    print $child &quot;Parent Pid $$ is sending this\n&quot;;
    chomp(my $line = &lt;$child&gt;);
    print &quot;Parent Pid $$ just read this: &#39;$line&#39;\n&quot;;
    close $child;
    waitpid($pid, 0);
} else {
    die &quot;cannot fork: $!&quot; unless defined $pid;
    close $child;
    chomp(my $line = &lt;$parent&gt;);
    print &quot;Child Pid $$ just read this: &#39;$line&#39;\n&quot;;
    print $parent &quot;Child Pid $$ is sending this\n&quot;;
    close $parent;
    exit(0);
}</code></pre>

<h1 id="Sockets:-Client/Server-Communication"><a class="permalink" href="perlipc.html#Sockets:-Client/Server-Communication">#</a><a id="Sockets"></a><a id="Sockets:-Client-Server-Communication"></a>Sockets: Client/Server Communication</h1>

<p>While not entirely limited to Unix-derived operating systems (e.g., WinSock on PCs provides socket support, as do some VMS libraries), you might not have sockets on your system, in which case this section probably isn&#39;t going to do you much good. With sockets, you can do both virtual circuits like TCP streams and datagrams like UDP packets. You may be able to do even more depending on your system.</p>

<p>The Perl functions for dealing with sockets have the same names as the corresponding system calls in C, but their arguments tend to differ for two reasons. First, Perl filehandles work differently than C file descriptors. Second, Perl already knows the length of its strings, so you don&#39;t need to pass that information.</p>

<p>One of the major problems with ancient, antemillennial socket code in Perl was that it used hard-coded values for some of the constants, which severely hurt portability. If you ever see code that does anything like explicitly setting <code>$AF_INET = 2</code>, you know you&#39;re in for big trouble. An immeasurably superior approach is to use the <a href="Socket.html">Socket</a> module, which more reliably grants access to the various constants and functions you&#39;ll need.</p>

<p>If you&#39;re not writing a server/client for an existing protocol like NNTP or SMTP, you should give some thought to how your server will know when the client has finished talking, and vice-versa. Most protocols are based on one-line messages and responses (so one party knows the other has finished when a &quot;\n&quot; is received) or multi-line messages and responses that end with a period on an empty line (&quot;\n.\n&quot; terminates a message/response).</p>

<h2 id="Internet-Line-Terminators"><a class="permalink" href="perlipc.html#Internet-Line-Terminators">#</a><a id="Internet"></a>Internet Line Terminators</h2>

<p>The Internet line terminator is &quot;\015\012&quot;. Under ASCII variants of Unix, that could usually be written as &quot;\r\n&quot;, but under other systems, &quot;\r\n&quot; might at times be &quot;\015\015\012&quot;, &quot;\012\012\015&quot;, or something completely different. The standards specify writing &quot;\015\012&quot; to be conformant (be strict in what you provide), but they also recommend accepting a lone &quot;\012&quot; on input (be lenient in what you require). We haven&#39;t always been very good about that in the code in this manpage, but unless you&#39;re on a Mac from way back in its pre-Unix dark ages, you&#39;ll probably be ok.</p>

<h2 id="Internet-TCP-Clients-and-Servers"><a class="permalink" href="perlipc.html#Internet-TCP-Clients-and-Servers">#</a><a id="Internet1"></a>Internet TCP Clients and Servers</h2>

<p>Use Internet-domain sockets when you want to do client-server communication that might extend to machines outside of your own system.</p>

<p>Here&#39;s a sample TCP client using Internet-domain sockets:</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use Socket;

my $remote  = shift || &quot;localhost&quot;;
my $port    = shift || 2345;  # random port
if ($port =~ /\D/) { $port = getservbyname($port, &quot;tcp&quot;) }
die &quot;No port&quot; unless $port;
my $iaddr   = inet_aton($remote)       || die &quot;no host: $remote&quot;;
my $paddr   = sockaddr_in($port, $iaddr);

my $proto   = getprotobyname(&quot;tcp&quot;);
socket(my $sock, PF_INET, SOCK_STREAM, $proto)  || die &quot;socket: $!&quot;;
connect($sock, $paddr)              || die &quot;connect: $!&quot;;
while (my $line = &lt;$sock&gt;) {
    print $line;
}

close ($sock)                        || die &quot;close: $!&quot;;
exit(0);</code></pre>

<p>And here&#39;s a corresponding server to go along with it. We&#39;ll leave the address as <code>INADDR_ANY</code> so that the kernel can choose the appropriate interface on multihomed hosts. If you want sit on a particular interface (like the external side of a gateway or firewall machine), fill this in with your real address instead.</p>

<pre><code>#!/usr/bin/perl -T
use strict;
use warnings;
BEGIN { $ENV{PATH} = &quot;/usr/bin:/bin&quot; }
use Socket;
use Carp;
my $EOL = &quot;\015\012&quot;;

sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime(), &quot;\n&quot; }

my $port  = shift || 2345;
die &quot;invalid port&quot; unless $port =~ /^ \d+ $/x;

my $proto = getprotobyname(&quot;tcp&quot;);

socket(my $server, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
setsockopt($server, SOL_SOCKET, SO_REUSEADDR, pack(&quot;l&quot;, 1))
                                              || die &quot;setsockopt: $!&quot;;
bind($server, sockaddr_in($port, INADDR_ANY)) || die &quot;bind: $!&quot;;
listen($server, SOMAXCONN)                    || die &quot;listen: $!&quot;;

logmsg &quot;server started on port $port&quot;;

for (my $paddr; $paddr = accept(my $client, $server); close $client) {
    my($port, $iaddr) = sockaddr_in($paddr);
    my $name = gethostbyaddr($iaddr, AF_INET);

    logmsg &quot;connection from $name [&quot;,
            inet_ntoa($iaddr), &quot;]
            at port $port&quot;;

    print $client &quot;Hello there, $name, it&#39;s now &quot;,
                    scalar localtime(), $EOL;
}</code></pre>

<p>And here&#39;s a multitasking version. It&#39;s multitasked in that like most typical servers, it spawns (fork()s) a slave server to handle the client request so that the master server can quickly go back to service a new client.</p>

<pre><code>#!/usr/bin/perl -T
use strict;
use warnings;
BEGIN { $ENV{PATH} = &quot;/usr/bin:/bin&quot; }
use Socket;
use Carp;
my $EOL = &quot;\015\012&quot;;

sub spawn;  # forward declaration
sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime(), &quot;\n&quot; }

my $port  = shift || 2345;
die &quot;invalid port&quot; unless $port =~ /^ \d+ $/x;

my $proto = getprotobyname(&quot;tcp&quot;);

socket(my $server, PF_INET, SOCK_STREAM, $proto) || die &quot;socket: $!&quot;;
setsockopt($server, SOL_SOCKET, SO_REUSEADDR, pack(&quot;l&quot;, 1))
                                              || die &quot;setsockopt: $!&quot;;
bind($server, sockaddr_in($port, INADDR_ANY)) || die &quot;bind: $!&quot;;
listen($server, SOMAXCONN)                    || die &quot;listen: $!&quot;;

logmsg &quot;server started on port $port&quot;;

my $waitedpid = 0;

use POSIX &quot;:sys_wait_h&quot;;
use Errno;

sub REAPER {
    local $!;   # don&#39;t let waitpid() overwrite current error
    while ((my $pid = waitpid(-1, WNOHANG)) &gt; 0 &amp;&amp; WIFEXITED($?)) {
        logmsg &quot;reaped $waitedpid&quot; . ($? ? &quot; with exit $?&quot; : &quot;&quot;);
    }
    $SIG{CHLD} = \&amp;REAPER;  # loathe SysV
}

$SIG{CHLD} = \&amp;REAPER;

while (1) {
    my $paddr = accept(my $client, $server) || do {
        # try again if accept() returned because got a signal
        next if $!{EINTR};
        die &quot;accept: $!&quot;;
    };
    my ($port, $iaddr) = sockaddr_in($paddr);
    my $name = gethostbyaddr($iaddr, AF_INET);

    logmsg &quot;connection from $name [&quot;,
           inet_ntoa($iaddr),
           &quot;] at port $port&quot;;

    spawn $client, sub {
        $| = 1;
        print &quot;Hello there, $name, it&#39;s now &quot;,
              scalar localtime(),
              $EOL;
        exec &quot;/usr/games/fortune&quot;       # XXX: &quot;wrong&quot; line terminators
            or confess &quot;can&#39;t exec fortune: $!&quot;;
    };
    close $client;
}

sub spawn {
    my $client = shift;
    my $coderef = shift;

    unless (@_ == 0 &amp;&amp; $coderef &amp;&amp; ref($coderef) eq &quot;CODE&quot;) {
        confess &quot;usage: spawn CLIENT CODEREF&quot;;
    }

    my $pid;
    unless (defined($pid = fork())) {
        logmsg &quot;cannot fork: $!&quot;;
        return;
    }
    elsif ($pid) {
        logmsg &quot;begat $pid&quot;;
        return; # I&#39;m the parent
    }
    # else I&#39;m the child -- go spawn

    open(STDIN,  &quot;&lt;&amp;&quot;, $client)   || die &quot;can&#39;t dup client to stdin&quot;;
    open(STDOUT, &quot;&gt;&amp;&quot;, $client)   || die &quot;can&#39;t dup client to stdout&quot;;
    ## open(STDERR, &quot;&gt;&amp;&quot;, STDOUT) || die &quot;can&#39;t dup stdout to stderr&quot;;
    exit($coderef-&gt;());
}</code></pre>

<p>This server takes the trouble to clone off a child version via fork() for each incoming request. That way it can handle many requests at once, which you might not always want. Even if you don&#39;t fork(), the listen() will allow that many pending connections. Forking servers have to be particularly careful about cleaning up their dead children (called &quot;zombies&quot; in Unix parlance), because otherwise you&#39;ll quickly fill up your process table. The REAPER subroutine is used here to call waitpid() for any child processes that have finished, thereby ensuring that they terminate cleanly and don&#39;t join the ranks of the living dead.</p>

<p>Within the while loop we call accept() and check to see if it returns a false value. This would normally indicate a system error needs to be reported. However, the introduction of safe signals (see <a href="perlipc.html#Deferred-Signals-%28Safe-Signals%29">&quot;Deferred Signals (Safe Signals)&quot;</a> above) in Perl 5.8.0 means that accept() might also be interrupted when the process receives a signal. This typically happens when one of the forked subprocesses exits and notifies the parent process with a CHLD signal.</p>

<p>If accept() is interrupted by a signal, $! will be set to EINTR. If this happens, we can safely continue to the next iteration of the loop and another call to accept(). It is important that your signal handling code not modify the value of $!, or else this test will likely fail. In the REAPER subroutine we create a local version of $! before calling waitpid(). When waitpid() sets $! to ECHILD as it inevitably does when it has no more children waiting, it updates the local copy and leaves the original unchanged.</p>

<p>You should use the <b>-T</b> flag to enable taint checking (see <a href="perlsec.html">perlsec</a>) even if we aren&#39;t running setuid or setgid. This is always a good idea for servers or any program run on behalf of someone else (like CGI scripts), because it lessens the chances that people from the outside will be able to compromise your system.</p>

<p>Let&#39;s look at another TCP client. This one connects to the TCP &quot;time&quot; service on a number of different machines and shows how far their clocks differ from the system on which it&#39;s being run:</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use Socket;

my $SECS_OF_70_YEARS = 2208988800;
sub ctime { scalar localtime(shift() || time()) }

my $iaddr = gethostbyname(&quot;localhost&quot;);
my $proto = getprotobyname(&quot;tcp&quot;);
my $port = getservbyname(&quot;time&quot;, &quot;tcp&quot;);
my $paddr = sockaddr_in(0, $iaddr);

$| = 1;
printf &quot;%-24s %8s %s\n&quot;, &quot;localhost&quot;, 0, ctime();

foreach my $host (@ARGV) {
    printf &quot;%-24s &quot;, $host;
    my $hisiaddr = inet_aton($host)     || die &quot;unknown host&quot;;
    my $hispaddr = sockaddr_in($port, $hisiaddr);
    socket(my $socket, PF_INET, SOCK_STREAM, $proto)
                                        || die &quot;socket: $!&quot;;
    connect($socket, $hispaddr)         || die &quot;connect: $!&quot;;
    my $rtime = pack(&quot;C4&quot;, ());
    read($socket, $rtime, 4);
    close($socket);
    my $histime = unpack(&quot;N&quot;, $rtime) - $SECS_OF_70_YEARS;
    printf &quot;%8d %s\n&quot;, $histime - time(), ctime($histime);
}</code></pre>

<h2 id="Unix-Domain-TCP-Clients-and-Servers"><a class="permalink" href="perlipc.html#Unix-Domain-TCP-Clients-and-Servers">#</a><a id="Unix"></a>Unix-Domain TCP Clients and Servers</h2>

<p>That&#39;s fine for Internet-domain clients and servers, but what about local communications? While you can use the same setup, sometimes you don&#39;t want to. Unix-domain sockets are local to the current host, and are often used internally to implement pipes. Unlike Internet domain sockets, Unix domain sockets can show up in the file system with an ls(1) listing.</p>

<pre><code class="plaintext">% ls -l /dev/log
srw-rw-rw-  1 root            0 Oct 31 07:23 /dev/log</code></pre>

<p>You can test for these with Perl&#39;s <b>-S</b> file test:</p>

<pre><code>unless (-S &quot;/dev/log&quot;) {
    die &quot;something&#39;s wicked with the log system&quot;;
}</code></pre>

<p>Here&#39;s a sample Unix-domain client:</p>

<pre><code>#!/usr/bin/perl
use Socket;
use strict;
use warnings;

my $rendezvous = shift || &quot;catsock&quot;;
socket(my $sock, PF_UNIX, SOCK_STREAM, 0) || die &quot;socket: $!&quot;;
connect($sock, sockaddr_un($rendezvous))  || die &quot;connect: $!&quot;;
while (defined(my $line = &lt;$sock&gt;)) {
    print $line;
}
exit(0);</code></pre>

<p>And here&#39;s a corresponding server. You don&#39;t have to worry about silly network terminators here because Unix domain sockets are guaranteed to be on the localhost, and thus everything works right.</p>

<pre><code>#!/usr/bin/perl -T
use strict;
use warnings;
use Socket;
use Carp;

BEGIN { $ENV{PATH} = &quot;/usr/bin:/bin&quot; }
sub spawn;  # forward declaration
sub logmsg { print &quot;$0 $$: @_ at &quot;, scalar localtime(), &quot;\n&quot; }

my $NAME = &quot;catsock&quot;;
my $uaddr = sockaddr_un($NAME);
my $proto = getprotobyname(&quot;tcp&quot;);

socket(my $server, PF_UNIX, SOCK_STREAM, 0) || die &quot;socket: $!&quot;;
unlink($NAME);
bind  ($server, $uaddr)                     || die &quot;bind: $!&quot;;
listen($server, SOMAXCONN)                  || die &quot;listen: $!&quot;;

logmsg &quot;server started on $NAME&quot;;

my $waitedpid;

use POSIX &quot;:sys_wait_h&quot;;
sub REAPER {
    my $child;
    while (($waitedpid = waitpid(-1, WNOHANG)) &gt; 0) {
        logmsg &quot;reaped $waitedpid&quot; . ($? ? &quot; with exit $?&quot; : &quot;&quot;);
    }
    $SIG{CHLD} = \&amp;REAPER;  # loathe SysV
}

$SIG{CHLD} = \&amp;REAPER;


for ( $waitedpid = 0;
      accept(my $client, $server) || $waitedpid;
      $waitedpid = 0, close $client)
{
    next if $waitedpid;
    logmsg &quot;connection on $NAME&quot;;
    spawn $client, sub {
        print &quot;Hello there, it&#39;s now &quot;, scalar localtime(), &quot;\n&quot;;
        exec(&quot;/usr/games/fortune&quot;)  || die &quot;can&#39;t exec fortune: $!&quot;;
    };
}

sub spawn {
    my $client = shift();
    my $coderef = shift();

    unless (@_ == 0 &amp;&amp; $coderef &amp;&amp; ref($coderef) eq &quot;CODE&quot;) {
        confess &quot;usage: spawn CLIENT CODEREF&quot;;
    }

    my $pid;
    unless (defined($pid = fork())) {
        logmsg &quot;cannot fork: $!&quot;;
        return;
    }
    elsif ($pid) {
        logmsg &quot;begat $pid&quot;;
        return; # I&#39;m the parent
    }
    else {
        # I&#39;m the child -- go spawn
    }

    open(STDIN,  &quot;&lt;&amp;&quot;, $client)
        || die &quot;can&#39;t dup client to stdin&quot;;
    open(STDOUT, &quot;&gt;&amp;&quot;, $client)
        || die &quot;can&#39;t dup client to stdout&quot;;
    ## open(STDERR, &quot;&gt;&amp;&quot;, STDOUT)
    ##  || die &quot;can&#39;t dup stdout to stderr&quot;;
    exit($coderef-&gt;());
}</code></pre>

<p>As you see, it&#39;s remarkably similar to the Internet domain TCP server, so much so, in fact, that we&#39;ve omitted several duplicate functions--spawn(), logmsg(), ctime(), and REAPER()--which are the same as in the other server.</p>

<p>So why would you ever want to use a Unix domain socket instead of a simpler named pipe? Because a named pipe doesn&#39;t give you sessions. You can&#39;t tell one process&#39;s data from another&#39;s. With socket programming, you get a separate session for each client; that&#39;s why accept() takes two arguments.</p>

<p>For example, let&#39;s say that you have a long-running database server daemon that you want folks to be able to access from the Web, but only if they go through a CGI interface. You&#39;d have a small, simple CGI program that does whatever checks and logging you feel like, and then acts as a Unix-domain client and connects to your private server.</p>

<h1 id="TCP-Clients-with-IO::Socket"><a class="permalink" href="perlipc.html#TCP-Clients-with-IO::Socket">#</a><a id="TCP"></a>TCP Clients with IO::Socket</h1>

<p>For those preferring a higher-level interface to socket programming, the IO::Socket module provides an object-oriented approach. If for some reason you lack this module, you can just fetch IO::Socket from CPAN, where you&#39;ll also find modules providing easy interfaces to the following systems: DNS, FTP, Ident (RFC 931), NIS and NISPlus, NNTP, Ping, POP3, SMTP, SNMP, SSLeay, Telnet, and Time--to name just a few.</p>

<h2 id="A-Simple-Client"><a class="permalink" href="perlipc.html#A-Simple-Client">#</a><a id="A"></a>A Simple Client</h2>

<p>Here&#39;s a client that creates a TCP connection to the &quot;daytime&quot; service at port 13 of the host name &quot;localhost&quot; and prints out everything that the server there cares to provide.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
my $remote = IO::Socket::INET-&gt;new(
                    Proto    =&gt; &quot;tcp&quot;,
                    PeerAddr =&gt; &quot;localhost&quot;,
                    PeerPort =&gt; &quot;daytime(13)&quot;,
                )
             || die &quot;can&#39;t connect to daytime service on localhost&quot;;
while (&lt;$remote&gt;) { print }</code></pre>

<p>When you run this program, you should get something back that looks like this:</p>

<pre><code class="plaintext">Wed May 14 08:40:46 MDT 1997</code></pre>

<p>Here are what those parameters to the new() constructor mean:</p>

<dl>

<dt id="Proto"><a class="permalink" href="perlipc.html#Proto">#</a><code>Proto</code></dt>
<dd>

<p>This is which protocol to use. In this case, the socket handle returned will be connected to a TCP socket, because we want a stream-oriented connection, that is, one that acts pretty much like a plain old file. Not all sockets are this of this type. For example, the UDP protocol can be used to make a datagram socket, used for message-passing.</p>

</dd>
<dt id="PeerAddr"><a class="permalink" href="perlipc.html#PeerAddr">#</a><code>PeerAddr</code></dt>
<dd>

<p>This is the name or Internet address of the remote host the server is running on. We could have specified a longer name like <code>&quot;www.perl.com&quot;</code>, or an address like <code>&quot;207.171.7.72&quot;</code>. For demonstration purposes, we&#39;ve used the special hostname <code>&quot;localhost&quot;</code>, which should always mean the current machine you&#39;re running on. The corresponding Internet address for localhost is <code>&quot;127.0.0.1&quot;</code>, if you&#39;d rather use that.</p>

</dd>
<dt id="PeerPort"><a class="permalink" href="perlipc.html#PeerPort">#</a><code>PeerPort</code></dt>
<dd>

<p>This is the service name or port number we&#39;d like to connect to. We could have gotten away with using just <code>&quot;daytime&quot;</code> on systems with a well-configured system services file,[FOOTNOTE: The system services file is found in <i>/etc/services</i> under Unixy systems.] but here we&#39;ve specified the port number (13) in parentheses. Using just the number would have also worked, but numeric literals make careful programmers nervous.</p>

</dd>
</dl>

<h2 id="A-Webget-Client"><a class="permalink" href="perlipc.html#A-Webget-Client">#</a><a id="A1"></a>A Webget Client</h2>

<p>Here&#39;s a simple client that takes a remote host to fetch a document from, and then a list of files to get from that host. This is a more interesting client than the previous one because it first sends something to the server before fetching the server&#39;s response.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
unless (@ARGV &gt; 1) { die &quot;usage: $0 host url ...&quot; }
my $host = shift(@ARGV);
my $EOL = &quot;\015\012&quot;;
my $BLANK = $EOL x 2;
for my $document (@ARGV) {
    my $remote = IO::Socket::INET-&gt;new( Proto     =&gt; &quot;tcp&quot;,
                                        PeerAddr  =&gt; $host,
                                        PeerPort  =&gt; &quot;http(80)&quot;,
              )     || die &quot;cannot connect to httpd on $host&quot;;
    $remote-&gt;autoflush(1);
    print $remote &quot;GET $document HTTP/1.0&quot; . $BLANK;
    while ( &lt;$remote&gt; ) { print }
    close $remote;
}</code></pre>

<p>The web server handling the HTTP service is assumed to be at its standard port, number 80. If the server you&#39;re trying to connect to is at a different port, like 1080 or 8080, you should specify it as the named-parameter pair, <code>PeerPort =&gt; 8080</code>. The <code>autoflush</code> method is used on the socket because otherwise the system would buffer up the output we sent it. (If you&#39;re on a prehistoric Mac, you&#39;ll also need to change every <code>&quot;\n&quot;</code> in your code that sends data over the network to be a <code>&quot;\015\012&quot;</code> instead.)</p>

<p>Connecting to the server is only the first part of the process: once you have the connection, you have to use the server&#39;s language. Each server on the network has its own little command language that it expects as input. The string that we send to the server starting with &quot;GET&quot; is in HTTP syntax. In this case, we simply request each specified document. Yes, we really are making a new connection for each document, even though it&#39;s the same host. That&#39;s the way you always used to have to speak HTTP. Recent versions of web browsers may request that the remote server leave the connection open a little while, but the server doesn&#39;t have to honor such a request.</p>

<p>Here&#39;s an example of running that program, which we&#39;ll call <i>webget</i>:</p>

<pre><code class="plaintext">% webget www.perl.com /guanaco.html
HTTP/1.1 404 File Not Found
Date: Thu, 08 May 1997 18:02:32 GMT
Server: Apache/1.2b6
Connection: close
Content-type: text/html

&lt;HEAD&gt;&lt;TITLE&gt;404 File Not Found&lt;/TITLE&gt;&lt;/HEAD&gt;
&lt;BODY&gt;&lt;H1&gt;File Not Found&lt;/H1&gt;
The requested URL /guanaco.html was not found on this server.&lt;P&gt;
&lt;/BODY&gt;</code></pre>

<p>Ok, so that&#39;s not very interesting, because it didn&#39;t find that particular document. But a long response wouldn&#39;t have fit on this page.</p>

<p>For a more featureful version of this program, you should look to the <i>lwp-request</i> program included with the LWP modules from CPAN.</p>

<h2 id="Interactive-Client-with-IO::Socket"><a class="permalink" href="perlipc.html#Interactive-Client-with-IO::Socket">#</a><a id="Interactive"></a>Interactive Client with IO::Socket</h2>

<p>Well, that&#39;s all fine if you want to send one command and get one answer, but what about setting up something fully interactive, somewhat like the way <i>telnet</i> works? That way you can type a line, get the answer, type a line, get the answer, etc.</p>

<p>This client is more complicated than the two we&#39;ve done so far, but if you&#39;re on a system that supports the powerful <code>fork</code> call, the solution isn&#39;t that rough. Once you&#39;ve made the connection to whatever service you&#39;d like to chat with, call <code>fork</code> to clone your process. Each of these two identical process has a very simple job to do: the parent copies everything from the socket to standard output, while the child simultaneously copies everything from standard input to the socket. To accomplish the same thing using just one process would be <i>much</i> harder, because it&#39;s easier to code two processes to do one thing than it is to code one process to do two things. (This keep-it-simple principle a cornerstones of the Unix philosophy, and good software engineering as well, which is probably why it&#39;s spread to other systems.)</p>

<p>Here&#39;s the code:</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;

unless (@ARGV == 2) { die &quot;usage: $0 host port&quot; }
my ($host, $port) = @ARGV;

# create a tcp connection to the specified host and port
my $handle = IO::Socket::INET-&gt;new(Proto     =&gt; &quot;tcp&quot;,
                                   PeerAddr  =&gt; $host,
                                   PeerPort  =&gt; $port)
           || die &quot;can&#39;t connect to port $port on $host: $!&quot;;

$handle-&gt;autoflush(1);       # so output gets there right away
print STDERR &quot;[Connected to $host:$port]\n&quot;;

# split the program into two processes, identical twins
die &quot;can&#39;t fork: $!&quot; unless defined(my $kidpid = fork());

# the if{} block runs only in the parent process
if ($kidpid) {
    # copy the socket to standard output
    while (defined (my $line = &lt;$handle&gt;)) {
        print STDOUT $line;
    }
    kill(&quot;TERM&quot;, $kidpid);   # send SIGTERM to child
}
# the else{} block runs only in the child process
else {
    # copy standard input to the socket
    while (defined (my $line = &lt;STDIN&gt;)) {
        print $handle $line;
    }
    exit(0);                # just in case
}</code></pre>

<p>The <code>kill</code> function in the parent&#39;s <code>if</code> block is there to send a signal to our child process, currently running in the <code>else</code> block, as soon as the remote server has closed its end of the connection.</p>

<p>If the remote server sends data a byte at time, and you need that data immediately without waiting for a newline (which might not happen), you may wish to replace the <code>while</code> loop in the parent with the following:</p>

<pre><code>my $byte;
while (sysread($handle, $byte, 1) == 1) {
    print STDOUT $byte;
}</code></pre>

<p>Making a system call for each byte you want to read is not very efficient (to put it mildly) but is the simplest to explain and works reasonably well.</p>

<h1 id="TCP-Servers-with-IO::Socket"><a class="permalink" href="perlipc.html#TCP-Servers-with-IO::Socket">#</a><a id="TCP1"></a>TCP Servers with IO::Socket</h1>

<p>As always, setting up a server is little bit more involved than running a client. The model is that the server creates a special kind of socket that does nothing but listen on a particular port for incoming connections. It does this by calling the <code>IO::Socket::INET-&gt;new()</code> method with slightly different arguments than the client did.</p>

<dl>

<dt id="Proto1"><a class="permalink" href="perlipc.html#Proto1">#</a>Proto</dt>
<dd>

<p>This is which protocol to use. Like our clients, we&#39;ll still specify <code>&quot;tcp&quot;</code> here.</p>

</dd>
<dt id="LocalPort"><a class="permalink" href="perlipc.html#LocalPort">#</a>LocalPort</dt>
<dd>

<p>We specify a local port in the <code>LocalPort</code> argument, which we didn&#39;t do for the client. This is service name or port number for which you want to be the server. (Under Unix, ports under 1024 are restricted to the superuser.) In our sample, we&#39;ll use port 9000, but you can use any port that&#39;s not currently in use on your system. If you try to use one already in used, you&#39;ll get an &quot;Address already in use&quot; message. Under Unix, the <code>netstat -a</code> command will show which services current have servers.</p>

</dd>
<dt id="Listen"><a class="permalink" href="perlipc.html#Listen">#</a>Listen</dt>
<dd>

<p>The <code>Listen</code> parameter is set to the maximum number of pending connections we can accept until we turn away incoming clients. Think of it as a call-waiting queue for your telephone. The low-level Socket module has a special symbol for the system maximum, which is SOMAXCONN.</p>

</dd>
<dt id="Reuse"><a class="permalink" href="perlipc.html#Reuse">#</a>Reuse</dt>
<dd>

<p>The <code>Reuse</code> parameter is needed so that we restart our server manually without waiting a few minutes to allow system buffers to clear out.</p>

</dd>
</dl>

<p>Once the generic server socket has been created using the parameters listed above, the server then waits for a new client to connect to it. The server blocks in the <code>accept</code> method, which eventually accepts a bidirectional connection from the remote client. (Make sure to autoflush this handle to circumvent buffering.)</p>

<p>To add to user-friendliness, our server prompts the user for commands. Most servers don&#39;t do this. Because of the prompt without a newline, you&#39;ll have to use the <code>sysread</code> variant of the interactive client above.</p>

<p>This server accepts one of five different commands, sending output back to the client. Unlike most network servers, this one handles only one incoming client at a time. Multitasking servers are covered in Chapter 16 of the Camel.</p>

<p>Here&#39;s the code.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
use Net::hostent;      # for OOish version of gethostbyaddr

my $PORT = 9000;       # pick something not in use

my $server = IO::Socket::INET-&gt;new( Proto     =&gt; &quot;tcp&quot;,
                                    LocalPort =&gt; $PORT,
                                    Listen    =&gt; SOMAXCONN,
                                    Reuse     =&gt; 1);

die &quot;can&#39;t setup server&quot; unless $server;
print &quot;[Server $0 accepting clients]\n&quot;;

while (my $client = $server-&gt;accept()) {
  $client-&gt;autoflush(1);
  print $client &quot;Welcome to $0; type help for command list.\n&quot;;
  my $hostinfo = gethostbyaddr($client-&gt;peeraddr);
  printf &quot;[Connect from %s]\n&quot;,
         $hostinfo ? $hostinfo-&gt;name : $client-&gt;peerhost;
  print $client &quot;Command? &quot;;
  while ( &lt;$client&gt;) {
    next unless /\S/;     # blank line
    if    (/quit|exit/i)  { last                                      }
    elsif (/date|time/i)  { printf $client &quot;%s\n&quot;, scalar localtime() }
    elsif (/who/i )       { print  $client `who 2&gt;&amp;1`                 }
    elsif (/cookie/i )    { print  $client `/usr/games/fortune 2&gt;&amp;1`  }
    elsif (/motd/i )      { print  $client `cat /etc/motd 2&gt;&amp;1`       }
    else {
      print $client &quot;Commands: quit date who cookie motd\n&quot;;
    }
  } continue {
     print $client &quot;Command? &quot;;
  }
  close $client;
}</code></pre>

<h1 id="UDP:-Message-Passing"><a class="permalink" href="perlipc.html#UDP:-Message-Passing">#</a><a id="UDP"></a>UDP: Message Passing</h1>

<p>Another kind of client-server setup is one that uses not connections, but messages. UDP communications involve much lower overhead but also provide less reliability, as there are no promises that messages will arrive at all, let alone in order and unmangled. Still, UDP offers some advantages over TCP, including being able to &quot;broadcast&quot; or &quot;multicast&quot; to a whole bunch of destination hosts at once (usually on your local subnet). If you find yourself overly concerned about reliability and start building checks into your message system, then you probably should use just TCP to start with.</p>

<p>UDP datagrams are <i>not</i> a bytestream and should not be treated as such. This makes using I/O mechanisms with internal buffering like stdio (i.e. print() and friends) especially cumbersome. Use syswrite(), or better send(), like in the example below.</p>

<p>Here&#39;s a UDP program similar to the sample Internet TCP client given earlier. However, instead of checking one host at a time, the UDP version will check many of them asynchronously by simulating a multicast and then using select() to do a timed-out wait for I/O. To do something similar with TCP, you&#39;d have to use a different socket handle for each host.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use Socket;
use Sys::Hostname;

my $SECS_OF_70_YEARS = 2_208_988_800;

my $iaddr = gethostbyname(hostname());
my $proto = getprotobyname(&quot;udp&quot;);
my $port = getservbyname(&quot;time&quot;, &quot;udp&quot;);
my $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick

socket(my $socket, PF_INET, SOCK_DGRAM, $proto) || die &quot;socket: $!&quot;;
bind($socket, $paddr)                           || die &quot;bind: $!&quot;;

$| = 1;
printf &quot;%-12s %8s %s\n&quot;,  &quot;localhost&quot;, 0, scalar localtime();
my $count = 0;
for my $host (@ARGV) {
    $count++;
    my $hisiaddr = inet_aton($host)         || die &quot;unknown host&quot;;
    my $hispaddr = sockaddr_in($port, $hisiaddr);
    defined(send($socket, 0, 0, $hispaddr)) || die &quot;send $host: $!&quot;;
}

my $rout = my $rin = &quot;&quot;;
vec($rin, fileno($socket), 1) = 1;

# timeout after 10.0 seconds
while ($count &amp;&amp; select($rout = $rin, undef, undef, 10.0)) {
    my $rtime = &quot;&quot;;
    my $hispaddr = recv($socket, $rtime, 4, 0) || die &quot;recv: $!&quot;;
    my ($port, $hisiaddr) = sockaddr_in($hispaddr);
    my $host = gethostbyaddr($hisiaddr, AF_INET);
    my $histime = unpack(&quot;N&quot;, $rtime) - $SECS_OF_70_YEARS;
    printf &quot;%-12s &quot;, $host;
    printf &quot;%8d %s\n&quot;, $histime - time(), scalar localtime($histime);
    $count--;
}</code></pre>

<p>This example does not include any retries and may consequently fail to contact a reachable host. The most prominent reason for this is congestion of the queues on the sending host if the number of hosts to contact is sufficiently large.</p>

<h1 id="SysV-IPC"><a class="permalink" href="perlipc.html#SysV-IPC">#</a><a id="SysV"></a>SysV IPC</h1>

<p>While System V IPC isn&#39;t so widely used as sockets, it still has some interesting uses. However, you cannot use SysV IPC or Berkeley mmap() to have a variable shared amongst several processes. That&#39;s because Perl would reallocate your string when you weren&#39;t wanting it to. You might look into the <code>IPC::Shareable</code> or <code>threads::shared</code> modules for that.</p>

<p>Here&#39;s a small example showing shared memory usage.</p>

<pre><code>use IPC::SysV qw(IPC_PRIVATE IPC_RMID S_IRUSR S_IWUSR);

my $size = 2000;
my $id = shmget(IPC_PRIVATE, $size, S_IRUSR | S_IWUSR);
defined($id)                    || die &quot;shmget: $!&quot;;
print &quot;shm key $id\n&quot;;

my $message = &quot;Message #1&quot;;
shmwrite($id, $message, 0, 60)  || die &quot;shmwrite: $!&quot;;
print &quot;wrote: &#39;$message&#39;\n&quot;;
shmread($id, my $buff, 0, 60)      || die &quot;shmread: $!&quot;;
print &quot;read : &#39;$buff&#39;\n&quot;;

# the buffer of shmread is zero-character end-padded.
substr($buff, index($buff, &quot;\0&quot;)) = &quot;&quot;;
print &quot;un&quot; unless $buff eq $message;
print &quot;swell\n&quot;;

print &quot;deleting shm $id\n&quot;;
shmctl($id, IPC_RMID, 0)        || die &quot;shmctl: $!&quot;;</code></pre>

<p>Here&#39;s an example of a semaphore:</p>

<pre><code>use IPC::SysV qw(IPC_CREAT);

my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 10, 0666 | IPC_CREAT);
defined($id)                    || die &quot;semget: $!&quot;;
print &quot;sem id $id\n&quot;;</code></pre>

<p>Put this code in a separate file to be run in more than one process. Call the file <i>take</i>:</p>

<pre><code># create a semaphore

my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 0, 0);
defined($id)                    || die &quot;semget: $!&quot;;

my $semnum  = 0;
my $semflag = 0;

# &quot;take&quot; semaphore
# wait for semaphore to be zero
my $semop = 0;
my $opstring1 = pack(&quot;s!s!s!&quot;, $semnum, $semop, $semflag);

# Increment the semaphore count
$semop = 1;
my $opstring2 = pack(&quot;s!s!s!&quot;, $semnum, $semop,  $semflag);
my $opstring  = $opstring1 . $opstring2;

semop($id, $opstring)   || die &quot;semop: $!&quot;;</code></pre>

<p>Put this code in a separate file to be run in more than one process. Call this file <i>give</i>:</p>

<pre><code># &quot;give&quot; the semaphore
# run this in the original process and you will see
# that the second process continues

my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 0, 0);
die unless defined($id);

my $semnum  = 0;
my $semflag = 0;

# Decrement the semaphore count
my $semop = -1;
my $opstring = pack(&quot;s!s!s!&quot;, $semnum, $semop, $semflag);

semop($id, $opstring)   || die &quot;semop: $!&quot;;</code></pre>

<p>The SysV IPC code above was written long ago, and it&#39;s definitely clunky looking. For a more modern look, see the IPC::SysV module.</p>

<p>A small example demonstrating SysV message queues:</p>

<pre><code>use IPC::SysV qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRUSR S_IWUSR);

my $id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR);
defined($id)                || die &quot;msgget failed: $!&quot;;

my $sent      = &quot;message&quot;;
my $type_sent = 1234;

msgsnd($id, pack(&quot;l! a*&quot;, $type_sent, $sent), 0)
                            || die &quot;msgsnd failed: $!&quot;;

msgrcv($id, my $rcvd_buf, 60, 0, 0)
                            || die &quot;msgrcv failed: $!&quot;;

my($type_rcvd, $rcvd) = unpack(&quot;l! a*&quot;, $rcvd_buf);

if ($rcvd eq $sent) {
    print &quot;okay\n&quot;;
} else {
    print &quot;not okay\n&quot;;
}

msgctl($id, IPC_RMID, 0)    || die &quot;msgctl failed: $!\n&quot;;</code></pre>

<h1 id="NOTES"><a class="permalink" href="perlipc.html#NOTES">#</a>NOTES</h1>

<p>Most of these routines quietly but politely return <code>undef</code> when they fail instead of causing your program to die right then and there due to an uncaught exception. (Actually, some of the new <i>Socket</i> conversion functions do croak() on bad arguments.) It is therefore essential to check return values from these functions. Always begin your socket programs this way for optimal success, and don&#39;t forget to add the <b>-T</b> taint-checking flag to the <code>#!</code> line for servers:</p>

<pre><code>#!/usr/bin/perl -T
use strict;
use warnings;
use sigtrap;
use Socket;</code></pre>

<h1 id="BUGS"><a class="permalink" href="perlipc.html#BUGS">#</a>BUGS</h1>

<p>These routines all create system-specific portability problems. As noted elsewhere, Perl is at the mercy of your C libraries for much of its system behavior. It&#39;s probably safest to assume broken SysV semantics for signals and to stick with simple TCP and UDP socket operations; e.g., don&#39;t try to pass open file descriptors over a local UDP datagram socket if you want your code to stand a chance of being portable.</p>

<h1 id="AUTHOR"><a class="permalink" href="perlipc.html#AUTHOR">#</a>AUTHOR</h1>

<p>Tom Christiansen, with occasional vestiges of Larry Wall&#39;s original version and suggestions from the Perl Porters.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlipc.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>There&#39;s a lot more to networking than this, but this should get you started.</p>

<p>For intrepid programmers, the indispensable textbook is <i>Unix Network Programming, 2nd Edition, Volume 1</i> by W. Richard Stevens (published by Prentice-Hall). Most books on networking address the subject from the perspective of a C programmer; translation to Perl is left as an exercise for the reader.</p>

<p>The IO::Socket(3) manpage describes the object library, and the Socket(3) manpage describes the low-level interface to sockets. Besides the obvious functions in <a href="perlfunc.html">perlfunc</a>, you should also check out the <i>modules</i> file at your nearest CPAN site, especially <a href="http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_">http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_</a>. See <a href="perlmodlib.html">perlmodlib</a> or best yet, the <i>Perl FAQ</i> for a description of what CPAN is and where to get it if the previous link doesn&#39;t work for you.</p>

<p>Section 5 of CPAN&#39;s <i>modules</i> file is devoted to &quot;Networking, Device Control (modems), and Interprocess Communication&quot;, and contains numerous unbundled modules numerous networking modules, Chat and Expect operations, CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet, Threads, and ToolTalk--to name just a few.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
